package com.jbwz.web.security.controller;

import com.jbwz.web.common.base.BaseController;
import com.jbwz.web.common.res.ResponseJson;
import com.jbwz.web.common.util.BeanUtilCommon;
import com.jbwz.web.security.entity.Resource;
import com.jbwz.web.security.entity.vo.ResourceVO;
import com.jbwz.web.security.service.ResourceService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 资源 前端控制器
 *
 * @author yyh
 * @since 2021-08-23 22:42:40
 */
@RestController
@RequestMapping("/resource")
public class ResourceController extends BaseController {

  @Autowired ResourceService resourceService;

  @GetMapping("/list-tree")
  public ResponseJson listTree() {
    List<ResourceVO> result = resourceService.listMenuTree();
    return success(result);
  }

  @GetMapping("/list/{pid}")
  public ResponseJson listByPid(@PathVariable("pid") Long pid) {
    List<ResourceVO> result = resourceService.listByPid(pid);
    return success(result);
  }

  @GetMapping("/list-cc/{pid}")
  public ResponseJson listWithChildrenByMenuPid(@PathVariable("pid") Long pid) {
    List<ResourceVO> result = resourceService.listByPidWithChildren(pid);
    return success(result);
  }

  @PostMapping("/save")
  public ResponseJson save(@RequestBody @Validated ResourceVO vo) {
    resourceService.saveOrUpdateWithCheck(BeanUtilCommon.copy(vo, new Resource()));
    return success();
  }

  /**
   * 先不实现配置菜单名称
   *
   * @return
   */
  @PostMapping("/current-menu")
  public ResponseJson currentMenu() {
    return success();
  }

  @GetMapping("/del/{id}")
  public ResponseJson del(@PathVariable("id") Long id) {
    resourceService.removeById(id);
    return success();
  }

  @GetMapping("/detail/{id}")
  public ResponseJson detail(@PathVariable("id") Long id) {
    Resource e = resourceService.getById(id);
    return success(toVO(e));
  }

  private ResourceVO toVO(Resource e) {
    ResourceVO vo = new ResourceVO();
    BeanUtils.copyProperties(e, vo);
    return vo;
  }
}
